package com.guqinghan.guqinghan_02_systemfile;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.guqinghan.guqinghan_02_systemfile.utils.PermisionUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    读写sd卡
    动态申请权限
 */
public class WRSDActivity extends AppCompatActivity {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.iv_sdInput);
    }

    public void submitInfo(View view) {
        String info = editText.getText().toString();
        // 判断SD卡是否就绪
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(WRSDActivity.this,"SD卡就绪",Toast.LENGTH_LONG).show();

            // 获取SD卡的存储情况
            File ext = Environment.getExternalStorageDirectory(); // 获取SD卡的目录
            // 使用的，总的 5.94 GB/6.24 GB
            long usableSpace = ext.getUsableSpace();
            long totalSpace = ext.getTotalSpace();
            String usAbleSize = Formatter.formatFileSize(WRSDActivity.this, usableSpace);
            String totalSize = Formatter.formatFileSize(WRSDActivity.this, totalSpace);
            System.out.println(usAbleSize+"/"+totalSize);

            File file = new File(ext,"user.txt");
            try {
                Log.i("user","动态申请权限");
                // 动态申请权限
                PermisionUtils.verifyStoragePermission(WRSDActivity.this);
                FileOutputStream os = new FileOutputStream(file);
                os.write(info.getBytes());
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else Toast.makeText(WRSDActivity.this,"SD卡不存在或未挂载",Toast.LENGTH_LONG).show();

    }
}
